//
//  QQEngine.m
//  test1
//
//  Created by gengzhangjia on 15/8/4.
//  Copyright (c) 2015年 gengzhangjia. All rights reserved.
//

#import "QQEngine.h"

@interface QQEngine ()
@property (nonatomic, strong) NSString *QQAppId;
@property (nonatomic, strong) QQCallBackBlock callBackBlock;
@property (nonatomic, strong) TencentOAuth *tencentOAuth;

@end

@implementation QQEngine
+ (QQEngine *) shareQQSDKEngine
{
    static QQEngine *qqEngine =nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        qqEngine =[[QQEngine alloc] init];
    });
    
    return qqEngine;
}

-(instancetype)init
{
    self =[super init];
    if(self)
    {
        _QQAppId =[self readQQAppID];
        _tencentOAuth =[[TencentOAuth alloc] initWithAppId:_QQAppId andDelegate:self];
    }
    
    return self;
}

- (NSString*) readQQAppID
{
    NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
    NSArray *array = [infoDic objectForKey:@"CFBundleURLTypes"];
    NSString *QQAppID = nil;
    for (NSDictionary *dic in array) {
        NSString *name = [dic objectForKey:@"CFBundleURLName"];
        if (name && name.length > 0 && [name isEqualToString:@"tencentopenapi"]) {
            NSArray *QQArray = [dic objectForKey:@"CFBundleURLSchemes"];
            if (QQArray && QQArray.count > 0) {
                QQAppID = [QQArray objectAtIndex:0];
                QQAppID = [QQAppID substringFromIndex:[@"tencent" length]];
                break;
            }
        }
    }
    return QQAppID;
}


- (BOOL) canHandleOpenUrl:(NSURL *) URL
{
    return [TencentOAuth CanHandleOpenURL:URL];
}

- (BOOL) handleOpenUrl:(NSURL *) URL
{
    return [TencentOAuth HandleOpenURL:URL];
}

- (BOOL) isQQInstalled
{
    return [QQApiInterface isQQInstalled];
}

- (BOOL) isQQAppSupportAPI
{
    return [QQApiInterface isQQSupportApi];
}

- (void) sendReqWithObject:(QQBaseObject *) sendObj
                     block:(QQCallBackBlock) block
{
    QQResult *result =nil;
    if(![self isQQInstalled])
    {
        result =[QQResult notInstallApp];
        if(block)
        {
            block(result);
        }
        
        return;
    }
    else if(![self isQQAppSupportAPI])
    {
        result =[QQResult createConditionWithErrorCode:QQResultCodeNotSupportAPI resultInfo:@"请更新,现有版本不支持API"];
        if(block)
        {
            block(result);
        }
        
        return;
    }
    
    result =[sendObj verifyData];
    if(result)
    {
        if(block)
        {
            block(result);
        }
        return;
    }

    if([sendObj isKindOfClass:[QQAuthObject class]])
    {
        NSArray *permissions = [NSArray arrayWithObjects:@"all", nil];
        [_tencentOAuth authorize:permissions inSafari:NO];
    }
    else if([sendObj isKindOfClass:[QQLogOutObject class]])
    {
        [_tencentOAuth logout:self];
    }
    else {
        QQBaseReq *req =[sendObj messageObj];
        if(req){
            [QQApiInterface sendReq:req];
        }
    }
    
    _callBackBlock =block;
}

#pragma mark --TencentSessionDelegate
- (void)tencentDidLogin
{
    if (0 != [_tencentOAuth.accessToken length]) {
        //登陆成功，记录登录用户的OpenID、Token以及过期时间
        if(![_tencentOAuth getUserInfo]) {
            QQAuthResult *qqAuthResult = [QQAuthResult generalError];
            _callBackBlock(qqAuthResult);
            _callBackBlock = nil;
        }
    } else {
        //登陆失败
        if(_callBackBlock)
        {
            QQAuthResult *qqAuthResult = [QQAuthResult generalError];
            _callBackBlock(qqAuthResult);
            _callBackBlock = nil;
        }
    }
}

- (void)tencentDidNotLogin:(BOOL)cancelled
{
    if(_callBackBlock)
    {
        QQAuthResult *qqAuthResult = nil;
        if(cancelled)
        {
            qqAuthResult = [QQAuthResult userCancelError];
        }
        else
        {
            qqAuthResult = [QQAuthResult generalError];
        }
        _callBackBlock(qqAuthResult);
        _callBackBlock = nil;
    }
}

- (void)tencentDidNotNetWork
{
    //无网络连接，请设置网络
    if(_callBackBlock)
    {
        QQAuthResult *qqAuthResult = [QQAuthResult generalError];
        _callBackBlock(qqAuthResult);
        _callBackBlock = nil;
    }
}

- (void)tencentDidLogout
{
    if(_callBackBlock)
    {
        _callBackBlock(nil);
        _callBackBlock = nil;
    }
}

- (void)getUserInfoResponse:(APIResponse*) response
{
    if (_callBackBlock != nil) {
        QQAuthResult *qqAuthResult = [QQAuthResult parseData:response];
        qqAuthResult.accessToken = _tencentOAuth.accessToken;
        qqAuthResult.openId = _tencentOAuth.openId;
        qqAuthResult.expirationDate = _tencentOAuth.expirationDate;
        _callBackBlock(qqAuthResult);
        _callBackBlock = nil;
    }
}

#pragma mark - QQApiInterfaceDelegate
+ (void)onResp:(QQBaseResp *)resp
{
    switch (resp.type)
    {
        case ESENDMESSAGETOQQRESPTYPE:
        {
            SendMessageToQQResp *response = (SendMessageToQQResp *)resp;
            QQResult *result = [QQResult parseData:response];
            QQEngine *instance = [QQEngine shareQQSDKEngine];
            if(instance.callBackBlock)
                instance.callBackBlock(result);
        }
        default:
        {
            break;
        }
    }
}
@end
